/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Aug 9, 2007
 * 
 */

package org.biojava.services.das.registry;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.biojava.dasobert.das.Capabilities;
import org.biojava.dasobert.das.NoSuchCapabilityException;
import org.biojava.dasobert.dasregistry.Das1Validator;

import dasregistry.validation.Validator;

public class DasSourceTester {

	Pattern emailPattern;
	Pattern httpPattern;

	DasRegistrySql parent;

	public static final int STATUS_OK = 1;

	public DasSourceTester(DasRegistrySql parent) {
		emailPattern = Pattern
				.compile("^[A-Za-z0-9\\._%-]+@[A-Za-z0-9\\._%-]+\\.[A-Za-z]{2,4}$");
		httpPattern = Pattern.compile("^https?://");
		this.parent = parent;
	}

	/**
	 * returns: 1 - arguments o.k. 3 - server failed validataion test 4 -
	 * database error - could not add server to database 5 - unknown capability
	 * 6 - adminemail not a valid email address 7 - dasurl not valid 8 -
	 * description not valid 9 - coordSystem not valid 10 - capabilities not
	 * valid 11 - testCode not found. 12 - nickname already in use / invalid
	 * nickname 13 - url does not fit to DAS spec
	 * 
	 * @param url
	 * @param nickname
	 * @param adminemail
	 * @param description
	 * @param cs_types
	 * @param capabilities
	 * @param labels
	 * @param helperurl
	 * @param testCodes
	 * @param ontology
	 * @param ignoreValidation
	 *            flag if the validation atempt shouldbe made
	 * @return a defined return value
	 */
	public int testArguments(String url, String nickname, String adminemail,
			String description, String[] cs_types, List<String> capabilities,
			String[] labels, String helperurl, String[] testCodes,
			boolean ignoreValidation, String ontology) {

		System.out.println("testing arguments with ignoreValidation "
				+ ignoreValidation);
		System.out.println("description = " + description);
		// description=null;
		if (adminemail == null || adminemail.equals("")) {
			return 6;
		}
		if (url == null || url.equals("")){
			return 7;
		}
		if (description == null || description.equals("")) {
			return 8;
		}
		if (capabilities.size() < 1) {
			return 10;
		}
		
		if ((testCodes == null) || (testCodes.length != cs_types.length)
				|| (testCodes.length < 1)) {
			return 11;
		}
		if (!Capabilities.isBigFileFormat(capabilities.get(0))) {
			
			// test if start with http://

			Matcher m = httpPattern.matcher(url);
			if (!m.lookingAt()) {
				System.out.println("httpPattern does not match");
				return 7;
			}
			
			Das1Validator dsv = new Das1Validator();
			if (!dsv.validateURL(url)) {
				return 13;
			}
		}
		if (nickname == null) {
			return 12;
		}
		if (nickname.equals("")) {
			return 12;
		}
		if (nickname.length() > DasRegistrySql.MAX_NICKNAME_LENGTH) {
			return 12;
		}
		nickname = nickname.toLowerCase();
		// System.out.println("in RegisterService");

		boolean works = false;
		// check if new DAS service is valid

		// if ( ! ignoreValidation) {
		// works = checkDasServer(url,testCodes,capabilities,ontology);
		// Validator validator=new Validator();
		// validator.validate(DasRegistry.SPEC1_5, url, capabilities, dcsses,
		// validateOntology, updateDatabase, registry, auto_id);
		// DasRegistry.SPEC1_5,url, testCode, caps,ontology
		// if ( ! works ) {
		// 3 - server could not be contacted (checkDasServer failed)
		// System.err.println("server could not be contacted");
		// return 3 ;
		// }
		// }

		if (url.length() < 10) {
			System.out.println("url < 10");
			return 7;
		}


		boolean caps_ok = check_capabilities(capabilities);

		if (!caps_ok) {
			System.err.println("unknown capability detected");
			return 5;

		}

		// test the email adress
		boolean isValidEmail = checkEmail(adminemail);
		if (!isValidEmail) {
			return 6;
		}

		// everything went fine ...
		return STATUS_OK;

	}

	/*
	 * check if a DAS server is online
	 */
	// private boolean checkDasServer(String url,String[] testCode, String[]
	// caps,String ontology) {
	// boolean allok = true;
	// for ( int i =0 ; i< testCode.length;i++) {
	// String code = testCode[i];
	// boolean status = checkDasServer(url,code,caps, ontology);
	// if ( ! status )
	// allok = false;
	// }
	// return allok;
	// }

	/*
	 * check if a DAS server is online
	 */
	/*
	 * private boolean checkDasServer(String url,String testCode, String[] caps,
	 * String ontology) { // do DAS - DSN request to server. // protect from
	 * html characters
	 * 
	 * String[] okcaps = parent.validate(DasRegistry.SPEC1_5,url, testCode,
	 * caps,ontology); if ( Capabilities.allStatedAreValid(caps, okcaps)) return
	 * true ; else return false; }
	 */

	/* check that capabilities are valid */

	private boolean check_capabilities(List<String> capabilities) {

		boolean all_ok = true;
		// try {
		Capabilities[] caps = Capabilities
				.capabilitiesFromStrings(capabilities);
		// } catch (NoSuchCapabilityException e) {
		// TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		for (int i = 0; i < capabilities.size(); i++) {
			String c = capabilities.get(i);

			if (!Capabilities.exists(c)) {
				System.err.println("warning a capability was not found" + c);
				all_ok = false;
			}
		}
		return all_ok;
	}

	/** test that the given string looks like an email address */
	private boolean checkEmail(String email) {
		Matcher m = emailPattern.matcher(email);
		return m.matches();
	}

}
